package com.tj.collection.controller.chatter;

import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.api.Page;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.StringUtils;
import com.google.common.collect.Lists;
import com.jsoniter.output.JsonStream;
import com.kly.user.dto.chatter.Chatter;
import com.kly.user.service.ChatterService;
import com.tj.collection.aop.anno.LogEvent;
import com.tj.collection.bean.ApiResponse;
import com.tj.collection.common.RequestLocalInfo;
import com.tj.collection.common.Result;
import com.tj.collection.controller.BaseCompent;
import com.tj.collection.controller.chatter.request.AddChatterGoalRequest;
import com.tj.collection.controller.chatter.request.GetChatterGoalRequest;
import com.tj.collection.controller.chatter.request.ChatterDetailRequest;
import com.tj.collection.controller.chatter.request.ChatterListRequest;
import com.tj.collection.controller.chatter.request.ChatterModifyReq;
import com.tj.collection.controller.chatter.request.ChatterRequest;
import com.tj.collection.controller.chatter.response.ChatterDto;
import com.tj.collection.controller.chatter.response.ChatterDetailResp;
import com.tj.collection.controller.chatter.response.ChatterListResponse;
import com.tj.collection.controller.chatter.response.GetChatterConfigResponse;
import com.tj.collection.controller.chatter.response.TeamMemberResponse;
import com.tj.collection.controller.models.request.BindActions;
import com.tj.collection.db.domain.Admin;
import com.tj.collection.db.domain.ChatterGoalDto;
import com.tj.collection.db.domain.ChatterWorkingSet;
import com.tj.collection.db.enums.RoleKeyEnum;
import com.tj.collection.db.service.AdminRoleService;
import com.tj.collection.db.service.AdminService;
import com.tj.collection.db.service.ChatterOptService;
import com.tj.collection.db.service.ChatterWorkingSetService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/chatter")
@Api(value = "chatterController", tags = {"chatter相关页面处理接口"})
public class ChatterController extends BaseCompent {


    @Resource
    private ChatterService chatterService;
    @Resource
    AdminService adminService;
    @Resource
    ChatterOptService chatterOptService;
    @Resource
    AdminRoleService adminRoleService;
    @Resource
    ChatterWorkingSetService chatterWorkingSetService;


    @RequestMapping(value = "/list", method = {RequestMethod.POST})
    @ApiOperation("chatter列表接口")
    public Result<ChatterListResponse> chatterList(@RequestBody ChatterListRequest request) {
        final BaseCompent.AccountRole accountRole = getAccountRole();

        Map<String, Object> params = request.setUpQueryParams(request, accountRole);
        String serialize = JsonStream.serialize(params);
        final Integer chattersCnt = chatterService.getChattersCnt(serialize);
        if (chattersCnt == 0) {
            return Result.ok(new ChatterListResponse(Lists.newArrayList(), 0));
        }

        // 获取chatter列表
        List<Chatter> chatters = chatterService.getChatters(serialize, new Page(request.getPageSize(), request.getCurrent()));
        // 获取排班时间
        final Map<String, ChatterWorkingSet> chatterWorkingSets = chatterWorkingSetService.getChatterWorkingSetMap(chatters);

        // 获取后台账号信息
        final List<Admin> admins = adminService.listAllAdmin();
        final List<ChatterDto> chatterList = chatters.stream().map((Chatter chatter) -> ChatterDto.toDto(chatter, admins, chatterWorkingSets)).collect(Collectors.toList());
        return Result.ok(new ChatterListResponse(chatterList, chattersCnt));
    }

    @RequestMapping(value = "/detail", method = {RequestMethod.POST})
    @ApiOperation("chatter详细信息接口")
    public Result<ChatterDetailResp> chatterDetail(@RequestBody ChatterDetailRequest request) {
        Map<String, Object> params = request.setUpQueryParams(request);
        String serialize = JsonStream.serialize(params);
        List<Chatter> chatters = chatterService.getChatters(serialize, new Page());
        if (CollectionUtils.isEmpty(chatters)) {
            return Result.fail("No record exists");
        }
        final Chatter chatter = chatters.get(0);
        return Result.ok(ChatterDetailResp.toChatter(chatter));
    }

    @LogEvent(name = "modifyChatterInfo")
    @RequestMapping(value = "/update", method = {RequestMethod.POST})
    @ApiOperation("chatter信息修改操作")
    public Result update(@RequestBody ChatterModifyReq chatterModifyReq) {
        // 更新基本信息
        chatterService.updateChatter(ChatterModifyReq.toChatter(chatterModifyReq, RequestLocalInfo.getCurrentAdmin().getId()), null);
        // 更新排班时间
        chatterOptService.modifyChatterWorkingHour(chatterModifyReq.getChatterCode(), chatterModifyReq.getStartHour1(), chatterModifyReq.getEndHour1(), chatterModifyReq.getStartHour2(), chatterModifyReq.getEndHour2());
        return Result.ok();
    }

    @LogEvent(name = "addChatter")
    @RequestMapping(value = "/add", method = {RequestMethod.POST})
    @ApiOperation("添加chatter操作")
    public Result add(@RequestBody ChatterRequest chatter) {
        final String chatterCode = chatter.getAccount();
        final boolean isNumber = NumberUtil.isNumber(chatterCode);
        if (chatterCode.length() != 6) {
            return Result.fail("Chatter Account`s length should be 6 digits");
        }
        if (!isNumber) {
            return Result.fail("Chatter Account should be number");
        }
        if (chatter.getPassword().length() > 30) {
            return Result.fail("Password cannot be greater than 30 digits");
        }

        final Response response = chatterService.addChatter(ChatterRequest.toChatter(chatter, RequestLocalInfo.getCurrentAdmin().getId()), null);
        if (response != null && response.getCode() ==0) {
            chatterOptService.addChatterAdmin(chatterCode, RequestLocalInfo.getCurrentAdmin().getId());
            return Result.ok();
        } else if (response == null) {
            return Result.fail("Add chatter failed");
        }
        return Result.fail(response.getMsg());
    }

    @LogEvent(name = "removeChatter")
    @RequestMapping(value = "/delete", method = {RequestMethod.POST})
    @ApiOperation("chatter 删除操作")
    public Result delete(@RequestBody ChatterRequest chatter) {
        chatterService.deleteChatter(chatter.getChatterCode());
        return Result.ok();
    }


    @LogEvent(name = "bindModel")
    @RequestMapping(value = "/bindActions", method = {RequestMethod.POST})
    @ApiOperation("chatter绑定&解绑model操作")
    public Result bindAction(@RequestBody BindActions actions) {
        try {
            chatterService.bindRelationUpdate(actions.getChatterCode(), actions.getModelsCode(), actions.getAction());
        } catch (Exception e) {
            log.error("bindActionError, req:{}", JSONObject.toJSONString(actions), e);
        }
        return Result.ok();
    }

    /**
     * 获取团长角色下的chatter用户
     */
    @ApiOperation("获取团长角色下的chatter用户")
    @RequestMapping(value = "/team/members", method = {RequestMethod.POST})
    public Result<TeamMemberResponse> teamMembers() {
        final Long roleIdByRoleKey = adminRoleService.getRoleIdByRoleKey(RoleKeyEnum.TEAM_LEADER, null);
        if (roleIdByRoleKey == null) {
            return Result.ok(new TeamMemberResponse().setChatters(Lists.newArrayList()));
        }

        final List<Long> adminIdListByRoleIds = adminRoleService.getAdminIdListByRoleId(roleIdByRoleKey);
        if (CollectionUtils.isEmpty(adminIdListByRoleIds)) {
            return Result.ok(new TeamMemberResponse().setChatters(Lists.newArrayList()));
        }
        final List<Admin> adminListByIdList = adminService.getAdminListByIdList(adminIdListByRoleIds);
        if (CollectionUtils.isEmpty(adminIdListByRoleIds)) {
            return Result.ok(new TeamMemberResponse().setChatters(Lists.newArrayList()));
        }

        final List<TeamMemberResponse.TeamMember> teamMembers = adminListByIdList.parallelStream().map(TeamMemberResponse::getTeamMember).collect(Collectors.toList());
        return Result.ok(new TeamMemberResponse().setChatters(teamMembers));
    }

    /**
     * 获取团长角色关联账号
     */
    @ApiOperation("获取团长角色关联账号")
    @RequestMapping(value = "/list/members", method = {RequestMethod.POST})
    public Result<TeamMemberResponse> listGoal() {

        final AccountRole accountRole = getAccountRole();
        List<Long> adminIds;
        // 超管可以查看所有的关联账号
        if (accountRole.getHasViewAllDataPermission()) {
            adminIds = chatterOptService.listAllAdminIds();
        } else {
            // 其它角色只能特定的账号
            adminIds = chatterOptService.listAdminIds(RequestLocalInfo.getCurrentAdmin().getId());
            if (CollectionUtils.isEmpty(adminIds)) {
                return Result.ok(new TeamMemberResponse().setChatters(Lists.newArrayList()));
            }
        }
        final List<Admin> adminListByIdList = adminService.getAdminListByIdList(adminIds);
        if (CollectionUtils.isEmpty(adminIds)) {
            return Result.ok(new TeamMemberResponse().setChatters(Lists.newArrayList()));
        }

        final List<TeamMemberResponse.TeamMember> teamMembers = adminListByIdList.parallelStream().map(TeamMemberResponse::getTeamMember).collect(Collectors.toList());
        return Result.ok(new TeamMemberResponse().setChatters(teamMembers));
    }

    /**
     * 获取chatter指标
     */
    @ApiOperation("获取chatter指标")
    @RequestMapping(value = "/goal/detail", method = {RequestMethod.POST})
    public Result<GetChatterConfigResponse> getGoal(@RequestBody GetChatterGoalRequest getChatterGoalReq) {
        if (StringUtils.isEmpty(getChatterGoalReq.getChatterCode())) {
            return Result.fail("chatter code should not be empty");
        }
        final ChatterGoalDto chatterGoal = chatterOptService.getChatterGoal(getChatterGoalReq.getChatterCode());
        return Result.ok(GetChatterConfigResponse.toRsp(chatterGoal));
    }

    /**
     * 添加chatter指标
     */
    @LogEvent(name = "addGoal")
    @ApiOperation("添加chatter指标")
    @RequestMapping(value = "/goal/add", method = {RequestMethod.POST})
    public Result addGoal(@RequestBody AddChatterGoalRequest addChatterGoalReq) {
        if (StringUtils.isEmpty(addChatterGoalReq.getChatterCode())) {
            return Result.fail("chatter code should not be empty");
        }
        chatterOptService.addChatterGoal(addChatterGoalReq);
        return Result.ok();
    }

}
